//
//  MRCountryViewController.m
//  Travel_World
//
//  Created by dllo on 15/10/14.
//  Copyright © 2015年 TLS. All rights reserved.
//

#import "MRCountryViewController.h"
#import "QTAFNnetWorkTool.h"
#import "UIImageView+WebCache.h"
#import "MRCountryHot_cityModel.h"
#import "MRCountry_DiscountModel.h"
#import "MRScrollAndPageView.h"
#import "MRCountry_HotCityCollectionViewCell.h"
#import "MRCountry_FooterCollectionReusableView.h"
#import "MRCountry_DiscountTableViewCell.h"
#import "MRCountry_messageViewController.h"
#import "MRAllCity_ViewController.h"// 全部城市
#import "MRDiscount_ViewController.h"// 超值自由行,精彩当地游
#import "MRCityViewController.h"
#import "MRMapViewController.h"
#import "SSCollectionDataTool.h"
#import "TLS_countryModel.h"


@interface MRCountryViewController ()<UITableViewDataSource,UITableViewDelegate,UICollectionViewDataSource,UICollectionViewDelegate>

@property (nonatomic, strong) NSMutableDictionary *dic;

@property (nonatomic, strong) NSMutableArray *photoArr;

@property (nonatomic, strong) NSMutableArray *hot_cityArr;

@property (nonatomic, strong) NSMutableArray *discountArr;

@property (nonatomic, strong) UICollectionView *collectionView;

@property (nonatomic, strong) UITableView *tableView;

@property (nonatomic, strong) UIView *headerView;

@property (nonatomic, strong) UILabel *cityLabel;

@property (nonatomic, strong) UIButton *collection;

@end

@implementation MRCountryViewController

- (void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    
    self.tabBarController.tabBar.hidden = YES;

    self.navigationController.navigationBar.translucent = YES;
    //self.navigationController.navigationBar.tintColor = [UIColor whiteColor];
    
    [self.navigationController.navigationBar setBackgroundImage:[UIImage imageNamed:@"bigShadow"] forBarMetrics:UIBarMetricsCompact];
    self.navigationController.navigationBar.layer.masksToBounds = YES;
    
    self.navigationController.navigationBar.translucent = YES;
    
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"iconfont-genzongdingwei"] style:UIBarButtonItemStyleDone target:self action:@selector(mapPush)];
    
}

#pragma mark 打开地图界面的点击方法
- (void)mapPush
{
    NSLog(@"fjklsjka打开地图界面");
    
    MRMapViewController *mapVC = [[MRMapViewController alloc] init];
    
    NSString *url = [NSString stringWithFormat:@"http://open.qyer.com/qyer/map/city_list?client_id=qyer_ios&client_secret=cd254439208ab658ddf9&count=20&country_id=%@&lat=38.88261036070509&lon=121.5397574228773&oauth_token=55d7f8a1931dedc7d5a8f24ab63426d0&page=1&track_app_channel=App%%2520Store&track_app_version=6.7&track_device_info=iPhone5%%2C4&track_deviceid=41AE760B-510C-4778-AF4D-177B387E0F3B&track_os=ios%%25209.0.2&track_user_id=6852801&v=1",self.dic[@"id"]];
    mapVC.url = url;
    mapVC.content = self.dic[@"cnname"];
    
    [self.navigationController pushViewController:mapVC animated:YES];
    
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self createTableView];
    
    [self createHeaderView];
    
    [self createCollectionView];
    
    [self createData];
  
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(push) name:@"push" object:nil];
    
}

#pragma mark 通知中心的方法
- (void)push
{
    MRDiscount_ViewController *disVC = [[MRDiscount_ViewController alloc] init];
    NSString *url = [NSString stringWithFormat:@"http://open.qyer.com/qyer/discount/tickets_freewalker?client_id=qyer_ios&client_secret=cd254439208ab658ddf9&count=20&id=%@&lat=38.88265182207316&lon=121.5397977601244&oauth_token=55d7f8a1931dedc7d5a8f24ab63426d0&order=2&page=1&product_type=1016%%2C1018%%2C1020&time=1&track_app_channel=App%%2520Store&track_app_version=6.7&track_device_info=iPhone5%%2C4&track_deviceid=41AE760B-510C-4778-AF4D-177B387E0F3B&track_os=ios%%25209.0.2&track_user_id=6852801&type=1&v=1",self.dic[@"id"]];
    
    disVC.content = self.dic[@"cnname"];
    disVC.url = url;
    
    [self.navigationController pushViewController:disVC animated:YES];
}

-(void)createHeaderView
{
    self.headerView = [[UIView alloc]initWithFrame:CGRectMake(0, -330 * HEI, WIDTH, 330 * HEI)];
    self.headerView.backgroundColor = [UIColor whiteColor];
    [self.tableView addSubview:self.headerView];
    
    self.cityLabel = [[UILabel alloc] initWithFrame:CGRectMake(20 * WID, 290 * HEI, 200 * WID, 30 * HEI)];
//    self.cityLabel.textColor = [UIColor grayColor];
    [self.headerView addSubview:self.cityLabel];
    
    UIButton *all = [UIButton buttonWithType:UIButtonTypeSystem];
    [all setTitle:@"查看全部 >" forState:UIControlStateNormal];
    [all setTintColor:[UIColor grayColor]];
    [all addTarget:self action:@selector(click) forControlEvents:UIControlEventTouchUpInside];
    all.frame = CGRectMake(270 * WID, 290 * HEI, 85, 30 * HEI);
    
    [self.headerView addSubview:all];
    
    UIView *line = [[UIView alloc] initWithFrame:CGRectMake(20 * WID, 330 * HEI, WIDTH - 20 * WID, 1 * HEI)];
    line.backgroundColor = [UIColor grayColor];
    [self.headerView addSubview:line];
}

#pragma mark button的点击方法
- (void)click
{
    MRAllCity_ViewController *allVC = [[MRAllCity_ViewController alloc] init];
    
    NSString *url = [NSString stringWithFormat:@"http://open.qyer.com/place/city/get_city_list?client_id=qyer_ios&client_secret=cd254439208ab658ddf9&count=20&countryid=%@&lat=38.88261036070509&lon=121.5397574228773&oauth_token=55d7f8a1931dedc7d5a8f24ab63426d0&page=1&track_app_channel=App%%2520Store&track_app_version=6.7&track_device_info=iPhone5%%2C4&track_deviceid=41AE760B-510C-4778-AF4D-177B387E0F3B&track_os=ios%%25209.0.2&track_user_id=6852801&v=1",self.dic[@"id"]];
    
    allVC.url = url;
    
    [self.navigationController pushViewController:allVC animated:YES];
    
}

#pragma mark 数据解析
- (void)createData
{
    
    [QTAFNnetWorkTool getUrl:self.url body:nil hudSuperView:self.view result:QTJSON headerFile:nil success:^(id result) {
        
        self.dic = result[@"data"];
        
        self.hot_cityArr = [MRCountryHot_cityModel baseModelByArr:result[@"data"][@"hot_city"]];
        
        self.discountArr = [MRCountry_DiscountModel baseModelByArr:result[@"data"][@"new_discount"]];

        
        [self.tableView reloadData];
        [self.collectionView reloadData];
        
        [self createScrollView];
        
        self.cityLabel.text = [NSString stringWithFormat:@"%@城市",self.dic[@"cnname"]];
        
    }];
    
}

#pragma mark 创建轮播图
- (void)createScrollView
{
    
    NSMutableArray *picArr = [NSMutableArray array];
    
    
    [picArr addObjectsFromArray:self.dic[@"photos"]];
    
    MRScrollAndPageView *scrollView = [[MRScrollAndPageView alloc] initWithFrame:CGRectMake(0, 0, WIDTH, 270 * HEI) Arr:picArr];
    
//    scrollView.tag = 7;
    // 创建完collectionView之后记得将轮播图添加到collectionView上
//    NSLog(@"scrollView 图片%ld",picArr.count);
//    scrollView.backgroundColor = [UIColor blueColor];
    [self.headerView addSubview:scrollView];
    
    UILabel *cnname = [[UILabel alloc] initWithFrame:CGRectMake(40 * WID, 130 * HEI, 100 * WID, 40 * HEI)];
    cnname.text = self.dic[@"cnname"];
    cnname.textColor = [UIColor whiteColor];
    cnname.font = [UIFont systemFontOfSize:23];
    [self.headerView addSubview:cnname];
    
    UILabel *enname = [[UILabel alloc] initWithFrame:CGRectMake(40 * WID, 170 * HEI, 150 * WID, 20 * HEI)];
    enname.text = self.dic[@"enname"];
    enname.textColor = [UIColor whiteColor];
    enname.font = [UIFont systemFontOfSize:14];
    [self.headerView addSubview:enname];
    
    UILabel *content = [[UILabel alloc] initWithFrame:CGRectMake(40 * WID, 200 * HEI, 200 * WID, 50 * HEI)];
    content.text = self.dic[@"entryCont"];
    content.numberOfLines = 2;
    content.textColor = [UIColor whiteColor];
    content.font = [UIFont systemFontOfSize:14];
    [self.headerView addSubview:content];
    
    UIButton *button = [UIButton buttonWithType:UIButtonTypeSystem];
    button.frame = CGRectMake(220 * WID, 230 * HEI, 150 * WID, 30 * HEI);
    [button setTintColor:[UIColor whiteColor]];
    [button setTitle:@"国家实用信息 >" forState:UIControlStateNormal];
    [button setFont:[UIFont systemFontOfSize:14]];
    [button addTarget:self action:@selector(buttonClick) forControlEvents:UIControlEventTouchUpInside];
    [self.headerView addSubview:button];
    
    
    TLS_countryModel *model = [[TLS_countryModel alloc] init];
    model.cnname = self.dic[@"cnname"];
    [[SSCollectionDataTool shareSSCollectionDataToolWithModelType:CountryModel] createTabelWithModelType:CountryModel];
    
    self.collection = [UIButton buttonWithType:UIButtonTypeSystem];
    self.collection.frame = CGRectMake(280 * WID, 135 * HEI, 40 * WID, 40 * HEI);
    [self.collection addTarget:self action:@selector(collection:) forControlEvents:UIControlEventTouchUpInside];
    [self.headerView addSubview:self.collection];
    
    
    if ([[SSCollectionDataTool shareSSCollectionDataToolWithModelType:CountryModel] isIntable:model] == NotInTable) {
        
        [self.collection setImage:[UIImage imageNamed:@"iconfont-xihuan"] forState:UIControlStateNormal];
        
    } else {
        
        [self.collection setImage:[UIImage imageNamed:@"iconfont-xihuan(1)"] forState:UIControlStateNormal];
        
    }
    
}

#pragma mark 收藏方法
- (void)collection:(UIButton *)button
{
    
    TLS_countryModel *model = [[TLS_countryModel alloc] init];
    model.Id = self.dic[@"id"];
    model.cnname = self.dic[@"cnname"];
    model.enname = self.dic[@"enname"];
    model.photo = self.dic[@"photos"][0];
    
    SelectInTable result = [[SSCollectionDataTool shareSSCollectionDataToolWithModelType:CountryModel] isIntable:model];
    
    if (result == InTable) {
        model.cnname = self.dic[@"cnname"];
        
        UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"警告" message:@"是否取消收藏?" preferredStyle:UIAlertControllerStyleAlert];
        UIAlertAction *leftAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];
        UIAlertAction *rightAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDestructive handler:^(UIAlertAction *action) {
            
            [[SSCollectionDataTool shareSSCollectionDataToolWithModelType:CountryModel] deleteCollectoinData:model modelType:CountryModel];
            
            [self.collection setImage:[UIImage imageNamed:@"iconfont-xihuan"] forState:UIControlStateNormal];
            
        }];
        [alertController addAction:leftAction];
        [alertController addAction:rightAction];
        [self presentViewController:alertController animated:YES completion:nil];
        
    }else if(result == NotInTable) {
        
        UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"提示" message:@"是否收藏?" preferredStyle:UIAlertControllerStyleAlert];
        UIAlertAction *leftAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];
        UIAlertAction *rightAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDestructive handler:^(UIAlertAction *action) {
            

            [[SSCollectionDataTool shareSSCollectionDataToolWithModelType:CountryModel] inserCollectionData:model];
            
            [self.collection setImage:[UIImage imageNamed:@"iconfont-xihuan(1)"] forState:UIControlStateNormal];
            
        }];
        
        [alertController addAction:leftAction];
        [alertController addAction:rightAction];
        [self presentViewController:alertController animated:YES completion:nil];
    }else {
        
        NSLog(@"查询错误");
        
    }
    
}

#pragma mark 国家实用信息button的点击方法
- (void)buttonClick
{
    
    MRCountry_messageViewController *messVC = [[MRCountry_messageViewController alloc] init];
    messVC.url = self.dic[@"overview_url"];
    
    [self.navigationController pushViewController:messVC animated:YES];
    
}

#pragma mark 创建TableView
- (void)createTableView
{
    
    self.tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, WIDTH, HEIGHT + 64) style:UITableViewStyleGrouped];
    
    self.tableView.contentInset = UIEdgeInsetsMake(330 * HEI, 0, 0, 0);
    
//    self.tableView.backgroundColor = [UIColor redColor];
    
    [self.view addSubview:self.tableView];
    
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
 
    self.tableView.rowHeight = 90 * HEI;
}

#pragma mark tableView的cell的个数
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.discountArr.count;
}

#pragma mark 创建tableView的cell
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *reuse = @"reuse";
    MRCountry_DiscountTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:reuse];
    if (self.discountArr.count > indexPath.row) {
        if (!cell) {
            
            cell = [[MRCountry_DiscountTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:reuse];
            
        }
        
        MRCountry_DiscountModel *model = self.discountArr[indexPath.row];
        
        [cell.ImageView sd_setImageWithURL:[NSURL URLWithString:model.photo]placeholderImage:[UIImage imageNamed:@"placeholder"]];
        
        cell.title.text = model.title;
        cell.discount.text = model.priceoff;
        
        NSString *priceStr = model.price;
        NSString *price = [priceStr substringWithRange:NSMakeRange(4, priceStr.length-11)];
        cell.price.text = [NSString stringWithFormat:@"%@元起",price];
        
//        cell.price.text = [NSString stringWithFormat:@"%@元起",model.price];
  
        return cell;
    } else {
        
        return nil;
        
    }
}

#pragma mark tableView的点击方法
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (self.discountArr.count > indexPath.row) {
        
        MRCountry_messageViewController *messVC = [[MRCountry_messageViewController alloc] init];
        
        messVC.url = [NSString stringWithFormat:@"http://m.qyer.com/z/deal/%@/?source=app&client_id=qyer_ios&track_app_version=6.7&track_deviceid=41AE760B-510C-4778-AF4D-177B387E0F3B&track_user_id=6852801",[self.discountArr[indexPath.row] Id]];
        
        [self.navigationController pushViewController:messVC animated:YES];
    }
}

#pragma mark 创建CollectionView
- (void)createCollectionView
{
    
    UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc] init];
    flowLayout.itemSize = CGSizeMake(160 * WID, 90 * HEI);
    flowLayout.sectionInset = UIEdgeInsetsMake(10 * HEI, 20 * WID, 10 * HEI, 20 * WID);
    
    self.collectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(0, 0, WIDTH, 280 * HEI) collectionViewLayout:flowLayout];  
    
    self.collectionView.bounces = NO;
    self.collectionView.backgroundColor = [UIColor whiteColor];
    
    [self.view addSubview:self.collectionView];
    
    self.collectionView.delegate = self;
    self.collectionView.dataSource = self;
   
    // 注册cell
    [self.collectionView registerClass:[MRCountry_HotCityCollectionViewCell class] forCellWithReuseIdentifier:@"hotCity"];
    
    // 注册footerView

    [self.collectionView registerClass:[MRCountry_FooterCollectionReusableView class] forSupplementaryViewOfKind:UICollectionElementKindSectionFooter withReuseIdentifier:@"footerView"];
    flowLayout.footerReferenceSize = CGSizeMake(0, 70 * HEI);
    

    
    self.tableView.tableHeaderView = self.collectionView;
    
}

- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath
{
    
    MRCountry_FooterCollectionReusableView *footerView = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionFooter withReuseIdentifier:@"footerView" forIndexPath:indexPath];
    
    return footerView;
    
}

#pragma mark collectionView的cell的个数
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return self.hot_cityArr.count;
}

#pragma mark 创建collectionView的cell
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    MRCountry_HotCityCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"hotCity" forIndexPath:indexPath];
    if (self.hot_cityArr.count > indexPath.row) {
        
        MRCountryHot_cityModel * model = self.hot_cityArr[indexPath.row];
        
        [cell.ImageView sd_setImageWithURL:[NSURL URLWithString:model.photo]placeholderImage:[UIImage imageNamed:@"placeholder"]];
        
        cell.cnname.text = model.cnname;
        cell.enname.text = model.enname;
        
    }
    return cell;
}

#pragma mark collectionView的点击方法
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    MRCityViewController *cityVC = [[MRCityViewController alloc] init];
    
    NSString *url = [NSString stringWithFormat:@"http://open.qyer.com/qyer/footprint/city_detail?city_id=%@&client_id=qyer_ios&client_secret=cd254439208ab658ddf9&count=20&lat=38.88261036070509&lon=121.5397574228773&oauth_token=55d7f8a1931dedc7d5a8f24ab63426d0&page=1&track_app_channel=App%%2520Store&track_app_version=6.7&track_device_info=iPhone5%%2C4&track_deviceid=41AE760B-510C-4778-AF4D-177B387E0F3B&track_os=ios%%25209.0.2&track_user_id=6852801&v=1",[self.hot_cityArr[indexPath.row] Id]];
    
    cityVC.url = url;
    
    [self.navigationController pushViewController:cityVC animated:YES];
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
